package hub.cathome.interceptor;

import hub.cathome.entity.User;
import hub.cathome.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller("administratorInterceptor")
public class AdministratorInterceptor implements HandlerInterceptor {
    @Resource(name="userService")
    private UserService userService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        User user = (User) request.getSession().getAttribute("user");
        if(user!=null){
            request.setAttribute("loginInfo","通过session判断登录身份合法");
            return true;
        }else{
            User userInCookie = new User();
            Cookie[] cookie = request.getCookies();
            if(cookie==null||cookie.length<1){
                return false;
            }
            for(Cookie cookie1:cookie){
                if(cookie1.getName().equals("username")){
                    userInCookie.setUsername(cookie1.getValue());
                }
                if(cookie1.getName().equals("password")){
                    userInCookie.setPassword(Long.valueOf(cookie1.getValue()));
                }
            }
            if(userService.login(userInCookie.getUsername(), userInCookie.getPassword())>0){
                User logUser = userService.getUserByComplexName(userInCookie.getUsername());
                request.getSession().setAttribute("user",logUser);
                request.setAttribute("user",logUser);
                request.setAttribute("loginInfo","通过cookie登录");
                return true;
            }
        }
        return false;
    }
}
